﻿using Shop.Model.Advert;
using Shop.Model.DB;
using Shop.RemoteModel;
using Shop.RemoteModel.Advert.Model;
using Shop.Repository.LinqHelper;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.Model;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class AdvertRepository : ShopBaseRepository<DBAdvert, long>, IAdvertRepository
    {
        public AdvertRepository ( ISqlClientFactory factory ) : base(factory)
        {
        }
        public Result[] Query<Result> ( AdvertQueryParam query, IBasicPage paging, out int count ) where Result : class
        {
            paging.InitOrderBy("Id", true);
            return base.Query<Result>(query.ToWhere(), paging, out count);
        }
        public long Add ( AdvertAddArg add )
        {
            DBAdvert place = add.ConvertMap<AdvertAddArg, DBAdvert>();
            place.Id = IdentityHelper.CreateId();
            place.AdvertStatus = AdvertStatus.起草;
            place.StopTime = place.PutInEnd;
            place.ActualBegin = place.PutInBegin;
            base.Insert(place);
            return place.Id;
        }
        public void Stop ( DBAdvert advert )
        {
            if ( advert.AdvertStatus != AdvertStatus.启用 )
            {
                throw new ErrorException("shop.advert.status.error");
            }
            advert.AdvertStatus = AdvertStatus.停用;
            if ( !base.Update(a => a.AdvertStatus == AdvertStatus.停用, a => a.Id == advert.Id) )
            {
                throw new ErrorException("shop.advert.stop.fail");
            }
        }

        public void End ( DBAdvert advert )
        {
            if ( advert.AdvertStatus != AdvertStatus.投放中 )
            {
                throw new ErrorException("shop.advert.status.error");
            }
            advert.StopTime = DateTime.Now.ToLong();
            advert.AdvertStatus = AdvertStatus.结束;
            if ( !base.Update(advert, new string[]
            {
                "AdvertStatus",
                "StopTime"
            }) )
            {
                throw new ErrorException("shop.advert.end.fail");
            }
        }
        public void Enable ( DBAdvert advert )
        {
            if ( advert.AdvertStatus != AdvertStatus.起草 && advert.AdvertStatus != AdvertStatus.停用 )
            {
                throw new ErrorException("shop.advert.status.error");
            }
            if ( !base.Update(a => a.AdvertStatus == AdvertStatus.启用, a => a.Id == advert.Id) )
            {
                throw new ErrorException("shop.advert.enable.fail");
            }
        }
    }
}
